﻿package net.wangit.framework.util;

import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.wangit.context.LocalContext;
import net.wangit.framework.config.GlobalSettings;

/**
 * Response工具类，用于gzip压缩输出
 * 
 * @author watson
 * Feb 14, 2010
 */
public class ResponseUtil {

	private static final String GZIP = "gzip";
	private static final String DEFAULT_TYPE = "text/html";

	public ResponseUtil() {
	}

	public static OutputStream setting(HttpServletResponse response)
			throws Exception {
		return setting(response, ResponseUtil.DEFAULT_TYPE);
	}

	public static OutputStream setting(HttpServletResponse response, String type)
			throws Exception {
		LocalContext lc = LocalContext.getLocalContext();
		response.setContentType((new StringBuilder(String.valueOf(type)))
				.append(";charset=").append(GlobalSettings.getEncoding())
				.toString());
		response.addHeader("Cache-Control", "no-cache");
		response.addHeader("Cache-Control", "no-store");
		HttpServletRequest request = lc.getHttpServletRequest();
		String acceptEncoding = request.getHeader("Accept-Encoding");
		if (GlobalSettings.isGZIPEnabled() && acceptEncoding != null
				&& acceptEncoding.toLowerCase().indexOf(ResponseUtil.GZIP) >= 0) {
			response.addHeader("Content-Encoding", ResponseUtil.GZIP);
			return new GZIPOutputStream(response.getOutputStream());
		} else {
			return response.getOutputStream();
		}
	}
}
